/**
 * Sapien API.
 */
var SAPIEN = {};
/**
 * Action namespace.
 */
SAPIEN.action = {};
/**
 * Data namespace.
 */
SAPIEN.data = {};
/**
 * Sets the properties on a page using the object properties as an id.
 * @param {Object} obj The object containing the data.
 * @param {Object} formId (Optiona) form id.
 */
SAPIEN.data.setProperties = function (obj, formId) {
	var prefix = (formId === undefined) ? '#' : ('#' + formId + '_');
	$.each(obj, function (key, value) {
		var element = $(prefix + key);
		var type = element.attr('type');
		if (type === 'checkbox') {
			if (value === true) {
				element.attr('checked', 'checked');
			} else {
				element.removeAttr('checked');
			}
		} else {
			element.val(value);
		}
	});
};
SAPIEN.data.setCookie = function (name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = '; expires=' + date.toGMTString();
	}
	document.cookie = name + '=' + value + expires + '; path=/';
};
SAPIEN.data.readCookie = function (name) {
	var search = name + '=';
	var cookies = document.cookie.split(';');
	for (var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i];
		while (cookie.charAt(0) == ' ') {
			cookie = cookie.substring(1, cookie.length);
		}
		if (cookie.indexOf(search) == 0) {
			return cookie.substring(search.length, cookie.length);
		}
	}
	return null;
}
/**
 * An implmentation of a Collection.
 */
SAPIEN.data.Collection = function() {
	var self = this;
	var objects = {};
	var size = 0;
	/**
	 * Adds the object to the collection.
	 * @param {Object} obj The object to add. The object must have an id property.
	 */
	self.add = function (obj) {
		if (typeof obj === 'object' && obj.id !== undefined) {
			objects[obj.id] = obj;
			size++;
		}
	}
	/**
	 * Removes an object by the object's id property.
	 * @param {Object} id The id of the object to remove.
	 */
	self.remove = function (id) {
		delete objects[id];
		size--;
	}
	/**
	 * Returns an object with the given id.
	 * @param {Object} id The id of the object to return.
	 * @return {Object} the object with the given id.
	 */
	self.get = function (id) {
		return objects[id];
	}
	/**
	 * Returns the number of elements in the collection.
	 * @return {Number} the size.
	 */
	self.size = function() {
		return size;
	}
	self.test = function() {
		$.each(objects, function (i, val) {
			console.log('id = ' + val.id)
		});
	}
};
